package com.ty.blog.service.sys.impl;

import com.google.code.kaptcha.Producer;
import com.ty.blog.common.constant.RedisConstant;
import com.ty.blog.common.constant.RedisExpireDate;
import com.ty.blog.common.constant.SymbolConstant;
import com.ty.blog.common.exception.SKYException;
import com.ty.blog.common.utils.RedisUtils;
import com.ty.blog.common.utils.StringUtils;
import com.ty.blog.service.sys.SysCaptchaService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;

/**
 * @author zhutianyu
 * @date 2021/8/16 19:21
 */
@Service(value = "sysCaptchaService")
public class SysCaptchaServiceImpl implements SysCaptchaService {

    @Resource
    private Producer producer;

    @Resource
    RedisUtils redisUtils;

    @Override
    public BufferedImage getCaptcha(String uuid) {
        if (StringUtils.isBlank(uuid)) {
            throw new SKYException("系统异常");
        }
        String code = producer.createText();
        String key = RedisConstant.LOGIN_CAPTCHA.concat(SymbolConstant.POINT).concat(uuid).concat(SymbolConstant.POINT).concat(code);
        redisUtils.set(key, code, RedisExpireDate.FIVE_MINUTES);
        return producer.createImage(code);
    }

    @Override
    public Boolean validate(String uuid, String code) {
        if (StringUtils.isBlank(uuid)) {
            throw new SKYException("参数异常");
        }
        String key = RedisConstant.LOGIN_CAPTCHA.concat(SymbolConstant.POINT).concat(uuid).concat(SymbolConstant.POINT).concat(code);
        return redisUtils.exist(key);
    }
}
